//
//  DGGDES3Util.m
//  DES
//
//  Created by Toni on 12-12-27.
//  Copyright (c) 2012年 sinofreely. All rights reserved.
//

#import "DGGDES3Util.h"
#import "DGGGTMBase64.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation DGGDES3Util

const Byte iv[] = {1,2,3,4,5,6,7,8};

+(NSString *)encryptUseDES:(NSString *)plainText key:(NSString *)key{
    NSAssert(plainText, @"encryptString must not be nil！");
    NSAssert(key, @"encryptKey must not be nil！");
    NSString *ciphertext = nil;
    NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [textData length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          iv,
                                          [textData bytes], dataLength,
                                          buffer, 1024,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        ciphertext = [DGGGTMBase64 stringByEncodingData:data];
    }
    return ciphertext;
}

+(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key{
    NSString *plaintext = nil;
    NSData *plainData = [self decryptDataUseDES:cipherText key:key];
    if(plainData){
        plaintext = [[NSString alloc]initWithData:plainData encoding:NSUTF8StringEncoding];
    }
    return plaintext;
}

+ (NSData *)decryptDataUseDES:(NSString *)cipherText key:(NSString *)key{
    NSAssert(cipherText, @"decryptString must not be nil！");
    NSAssert(key, @"decryptKey must not be nil！");
    NSData *plaindata = nil;
    NSData *cipherdata = [DGGGTMBase64 decodeString:cipherText];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          iv,
                                          [cipherdata bytes], [cipherdata length],
                                          buffer, 1024,
                                          &numBytesDecrypted);
    if(cryptStatus == kCCSuccess)
    {
        plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
    }
    return plaindata;
}

@end
